<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类型" prop="goodType">
        <el-select v-model="queryParams.goodType" placeholder="请选择商品类型ID" clearable size="small">
          <el-option
            v-for="dict in goodTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
        <el-table-column label="主键" align="center" prop="id" v-if="false"/>
        <el-table-column label="商品名称" align="center" prop="name"/>
        <el-table-column label="商品类型" align="center" prop="goodType">
          <template slot-scope="scope">
            <dict-tag :options="goodTypeOptions" :value="scope.row.goodType"/>
          </template>
        </el-table-column>
        <el-table-column label="商品单价" align="center" prop="price"/>
        <el-table-column label="备注" align="center" prop="remark" v-if="false"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleAddFmOrderGoodsDetail(scope.row)"
              v-hasPermi="['fm:goods:edit']"
            >加入购物车
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <el-divider></el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteFmOrderGoodsDetail">删除
          </el-button>
        </el-col>
        <el-col :span="30">
          <el-form-item label="总金额" prop="money">
            <el-input :value="totalMoney" placeholder="请输入金额" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="100">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table :data="fmOrderGoodsDetailList" @selection-change="handleFmOrderGoodsDetailSelectionChange"
                ref="fmOrderGoodsDetail">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="编号" align="center" prop="index" width="50"/>
        <el-table-column label=" 商品名称" prop="name">
          <template slot-scope="scope">
            <el-input v-model="fmOrderGoodsDetailList[scope.$index].name" placeholder="请输入单价"/>
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="prize">
          <template slot-scope="scope">
            <el-input v-model="fmOrderGoodsDetailList[scope.$index].prize" placeholder="请输入单价"/>
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="num">
          <template slot-scope="scope">
            <el-input-number v-model="fmOrderGoodsDetailList[scope.$index].num" @change="handleChange(scope.row)"
                             :min="1" :max="100" label="数量" :style="{width:'120px'}"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="notice">
          <template slot-scope="scope">
            <el-input v-model="fmOrderGoodsDetailList[scope.$index].notice" placeholder="请输入备注"/>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

  </div>
</template>

<script>
import {listGoods, getGoods, delGoods, addGoods, updateGoods, exportGoods} from "@/api/fm/goods";
import {addGoodOrder} from "@/api/fm/goodOrder";

export default {
  name: "Goods",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 商品类型ID字典
      goodTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        goodType: null,
      },
      // 子表选中数据
      checkedFmOrderGoodsDetail: [],
      // 订单商品详情表格数据
      fmOrderGoodsDetailList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        prize: [
          {required: true, message: "请添加商品", trigger: 'onSubmit' },
          {type:"number" ,min: 1, max: 65535, message: '请添加商品', trigger: 'onSubmit'}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("fm_good_type").then(response => {
      this.goodTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        loginId: null,
        createTime: null,
        serial: null,
        money: null,
        remark: null,
        status: 0
      };
      this.fmOrderGoodsDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.money = this.totalMoney;
      if(this.fmOrderGoodsDetailList.length<1)
      {
        alert("请选择商品")
        return
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.fmOrderGoodsDetailList = this.fmOrderGoodsDetailList;
          addGoodOrder(this.form).then(response => {
            this.msgSuccess("新增成功");
            this.end();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    handleChange(row) {
    },
    /** 订单商品详情添加按钮操作 */
    handleAddFmOrderGoodsDetail(row) {
      let fmOrderGoodsDetailList2 = this.fmOrderGoodsDetailList.filter((row2) => {
        return row2.index === row.id;
      })
      if (fmOrderGoodsDetailList2.length > 0) {
        fmOrderGoodsDetailList2[0].num++;
        return;
      }
      let obj = {};
      obj.index = row.id
      obj.name = row.name;
      obj.prize = row.price;
      obj.num = "1";
      obj.notice = "";
      this.fmOrderGoodsDetailList.push(obj);
    },
    /** 订单商品详情删除按钮操作 */
    handleDeleteFmOrderGoodsDetail() {
      if (this.checkedFmOrderGoodsDetail.length == 0) {
        this.msgError("请先选择要删除的订单商品详情数据");
      } else {
        const fmOrderGoodsDetailList = this.fmOrderGoodsDetailList;
        const checkedFmOrderGoodsDetail = this.checkedFmOrderGoodsDetail;
        this.fmOrderGoodsDetailList = fmOrderGoodsDetailList.filter(function (item) {
          return checkedFmOrderGoodsDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleFmOrderGoodsDetailSelectionChange(selection) {
      this.checkedFmOrderGoodsDetail = selection.map(item => item.index)
    },
    end() {
      this.fmOrderGoodsDetailList = [];
      this.$emit("end", 1)
    }
  },
  computed:
    {
      totalMoney: function () {
        let money = 0;
        this.fmOrderGoodsDetailList.forEach((good) => {
          money = money + (good.prize * good.num);
        })
        return money
      }
    },

};
</script>
